import threading
import requests
import time

from common_tool import common_AddMission, common_GetMission, common_SaveCache


class Download_mission(threading.Thread):
    def __init__(self, thread_name: str,) -> None:
        super().__init__()
        self._thread_name = thread_name

    def run(self) -> None:
        while True:
            mission, length = common_GetMission()
            if mission == None:
                print(f'{self._thread_name} 下载完成')
                break
            print(f'{self._thread_name} 下载:{mission["url"]} 还剩:{length}')
            try:
                res = requests.get(url=mission['url'], timeout=10)
                content = res.content
                common_SaveCache(content=content, mission=mission)
            except Exception as e:
                common_AddMission(mission=mission)
                print(f'{self._thread_name} {mission["url"]} 下载失败继续添加 \n{e}')
            time.sleep(1)
